const app = getApp();
const publicFun = require('/utils/public.js');
const amapFile = require('/utils/amap.js');
import { getJianSuQuestions, setSubmitJianSu, getJianSuTimes } from '/utils/request'

var myAmapFun = new amapFile.AMapWX({key:'d1d1a1a1e2ea12099e41ff1ab23a9f19'});
var timer = null;
var thisIndex = 0;
var upIndex = 0;

Page({
  data: {
    carbonList: [],
    questionIdArr: [],
    exampleState: false,
    submitMask: false,
    addressState: false,

    btnDisabled: true,
    addressList: [],
    addressLocation: null,
    number: 0
  },
  onLoad() {
    this.setData({
      userid: app.globalData.userid,
      carbonList: [], 
      addressList: [],
      systemInfo: app.globalData.systemInfo,
    })
    my.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#ffffff',
    });
  
    this.getQAList();
    this.getScopeLocation(); //获取位置信息是否授权
  },

  openPos() {
    let that = this;
    if(this.data.addressList.length > 0){
      this.getAddressList();
      this.setData({
        addressState: true
      })
    }else{
      try {
        app.getLocation().then((location) => {
          that.getScopeLocation()
        }).catch((error) => {
          if(error == 2002){
            my.openSetting({
              success: () => {
                app.getLocation().then((location) => {
                  that.getScopeLocation()
                })
              }
            })
          }
        });
      }catch(e) {
        publicFun.showToast('失败，请稍后再试')
      }
    }
  },
  selectAddress(e) { //选择位置-地址列表
    let data = e.currentTarget.dataset.item;
    this.getTimes(data.name);
    this.setData({
      addressState: false,
      addressLocation: data
    });
  },
  closeAlert() { // 关闭附近地址
    this.setData({
      addressState: false,
      submitMask: false,
    })
  },

  // 提交
  submitBtn() { 
    this.data.carbonList.forEach((item, index) => {
      if(item.Type == "pics"){
        this.data.carbonList[index].uploadList = [];
      }
    })
    this.setData({ answerstr: '', carbonList: this.data.carbonList});

    if(!this.data.addressLocation.name){
      this.openPos();
      return false;
    }

    let allList = this.data.carbonList;
    for(let j=0; j<allList.length; j++) {
      if(allList[j].IsMust > 0 && allList[j].state){
        if(allList[j].Options.length > 0){
          let checked = allList[j].Options.some(i => i.checked == true); //是否有true的选项
          if(checked){
            // console.log(allList[j].QuestionId + '为true')
          }else{
              publicFun.showToast("* 为必选题，请补充完整");
              return false;
          }
        }else{
          if(allList[j].Type == "pics" && allList[j].imgList.length == 0) {
            publicFun.showToast("请拍摄至少一张现场照片");
            return false;
          }
        }
      }
    }
    // console.log("校验完毕");

    this.setData({
      submitMask: true,
    })
  },
  submitTap() {
    let allList = this.data.carbonList;
    this.setData({ submitMask: false});
    let result = allList.some(ele => {
      if(ele.Type == 'pics'){
        return ele.imgList.length > 0;
      }
    })
    if(result){
      this.recursionArr(allList); //递归 已答题
    }else{
      this.getanswerstr(); // 选择的选项进行拼接
    }
  },
  recursionArr(list) {
    list.map((item, index) => {
      // 对数据进行处理
      if(item.Type == "pics"){
        if(item.imgList.length > 0){
          this.recursionArr(item.imgList);
          my.showLoading();
          upIndex++;
          let successUp = 0;
          let failUp = 0;
          let i = 0;
          this.subImg(item.imgList, successUp, failUp, i, item.imgList.length, index);
        }
      }
  });
  },
  subImg(filePaths, successUp, failUp, i, length, tIndex) { //上传照片
    my.uploadFile({
      url: publicFun.api.commonImg,
      header: {'content-type': 'application/x-www-form-urlencoded'},
      fileType: 'image',
      fileName: 'filename',
      filePath: filePaths[i],
      formData: {
        uid: app.globalData.userid,
        miyao: app.getMiYao()
      },
      hideLoading: true,
      success: res => {
        let ress = JSON.parse(res.data);
        if(ress.S == 1){
          this.data.carbonList[tIndex].uploadList.push(ress.rpath);
          this.setData({
            carbonList: this.data.carbonList
          });
        }
        successUp++;
      },
      fail: res => {
        failUp++;
      },
      complete: (ress) => {
        i++;
        if (i == length) {
          // console.log("传完了");
          thisIndex++;
          this.getanswerstr();
        } else { //递归调用uploadDIY函数
          this.subImg(filePaths, successUp, failUp, i, length, tIndex);
        }
      }
    })
  },
  getanswerstr() {
    // 字符串拼接
    let str = "";
    let answer = "((##--***answer***--##))";
    let question = "((##--***question***--##))";
    this.data.carbonList.forEach(item => {
      // 选择
      if(item.Options.length > 0) {
        let checked = item.Options.some(i => i.checked == true); // 是否有true的选项
        if(checked){
          str += item.QuestionId + answer;
          item.Options.forEach(oItem => {
            if(oItem.checked){
              str += oItem.K + question;
            }
          })
        }
      }

      // 图片
      if(item.imgList){
        if(item.imgList.length > 0){
          str += item.QuestionId+answer;
          item.uploadList.forEach(imgUrl => {
            str += imgUrl + question
          })
        }
      }
    })

    this.setData({answerstr: str});
    if(thisIndex == upIndex){
      this.submitClass(); // 最后接口
    }
  },
  async submitClass() {
    let location = this.data.addressLocation;
    try{
      let params = {
        menuid: app.globalData.menuid,
        industryid: 0,
        userid: app.globalData.userid,
        industryname: location.name, // 企业名称或者门店名称
        province: location.province, //省份
        city: location.city, // 城市
        area: location.area, // 区县
        address: location.address, // 地址
        lat: app.globalData.location.lat, // 纬度
        lng: app.globalData.location.lng, // 经度
        answerstr: this.data.answerstr,
        jianyi: this.data.describe ? this.data.describe : '',
        gaodeclass: location.type,
        gaodesubclass: '',
      }
      const res = await setSubmitJianSu(params);
      my.hideLoading();
      if(res.S == 1){
        publicFun.showToast(res.M);
        let arrList = this.data.carbonList;
        let imgUrl = null;
        arrList.forEach(item => {
          if(item.QuestionId == res.TongBuImg){
            imgUrl = item.imgList[0];
          }
        })
        setTimeout(() => {
          my.navigateBack();
          my.setStorage({
            key: 'byoimgurl',
            data: imgUrl
          }); 
        }, 1000);
      }else{
        publicFun.showToast(res.M ? res.M : '提交失败');
      }
    }catch(e) {
      my.hideLoading();
      publicFun.showToast('失败，请稍后再试')
      app.globalData.tabPage = 1;
    }
  },
  getQuestionId() { // 暂时未用到
    this.setData({ questionIdArr: [] });
    this.data.carbonList.forEach(item => {
      if(item.Options.length > 0) { //单选
        let checked = item.Options.some(i => i.checked == true); //是否有true的选项
        if(checked){
          if(item.JoinId == 0){ // 一级问题
            this.data.questionIdArr.push(item)
          }
        }
      }
    })

    return this.data.questionIdArr;
  },
  

  bindTextAreaInput(e) { // 你还观察到什么
    this.setData({
      describe: e.detail.value
    });
  },
  changeFun(e) {
    let data = e.currentTarget.dataset;
    let item = data.item; // 父级
    let oitem = data.oitem; // 当前

    let listAll = this.data.carbonList;
    let filterIdArr = listAll.filter(i=>i.JoinId == item.QuestionId); // 符合的选项
    let filterArr = filterIdArr.filter(s=>(oitem.K & s.JoinType) > 0);

    filterIdArr.forEach(fItem => {
      fItem.state = false;
      fItem.Options.forEach(osItem => {
        osItem.checked = false;
        if(fItem.Type == "radio_zidaibei"){
          osItem.url = '/images/question/icon_'+osItem.K+'.png'
        }
      })
      if(fItem.Type == "pics"){
        fItem.imgList = [];
      }
      
      let ofIdArr = listAll.filter(i=>i.JoinId == fItem.QuestionId); // 联动符合的选项
      if(ofIdArr.length > 0){
        ofIdArr.forEach(ofItem => {
          ofItem.state = false;
          ofItem.imgList = [];
        })
      }
    })

    listAll.forEach(list => { 
      if(list.QuestionId == item.QuestionId) {
        list.Options.forEach(j => {
          if(j.K == oitem.K){
            if(!j.checked || j.checked == false){
              j.checked = true;
              filterArr.forEach(fItem => {
                fItem.state = true;
              })
              if(list.Type == "radio_zidaibei"){
                j.url = '/images/question/icon_yes'+j.K+'.png'
              }
            }else{
              j.checked = false;
              if(list.Type == "radio_zidaibei"){
                j.checked = true;
                return;
              }
            }
          }else{
            j.checked = false;
            if(list.Type == "radio_zidaibei"){
              j.url = '/images/question/icon_no'+j.K+'.png'
            }
          }
        })
      }
    })
    this.setData({
      carbonList: listAll
    })
  },
  
  async getQAList() { // 获取减塑问卷
    my.showLoading();
    try{
      let params = {
        menuid: app.globalData.menuid
      }
      const res = await getJianSuQuestions(params);
      my.hideLoading();
      if(res.S == 1){
        res.L.forEach(item => {
          if(item.Options.length > 0) {
            item.Options.forEach(oItem => {
              oItem.checked = false;
              if(item.Type == "radio_zidaibei"){
                oItem.url = '/images/question/icon_'+oItem.K+'.png'
              }
              
              if(oItem.V.includes("happy")){
                oItem = this.getEmojsImg(oItem);
              }
            })
          }
          if(item.TrType > 1 || item.JoinId > 0){
            item.state = false;
          }else{
            item.state = true;
            item.imgList = [];
          }

          if(item.Type == 'pics'){
            item.imgList = [];
            item.uploadList = [];
          }
        })
        this.setData({
          carbonList: res.L
        })
      }else{
        publicFun.showToast(res.M ? res.M : '加载失败');
      }
    }catch(e) {
      my.hideLoading();
      publicFun.showToast('失败，请稍后再试')
    }
  },
  getEmojsImg(oItem) {
    if (oItem.V.includes("(unhappy)")){
      oItem.V = oItem.V.replace("(unhappy)", '');
      oItem.emoji = '/images/question/icon_emoji_unhappy.png';
    }else{
      // oItem.V = oItem.V.replace("(happy)", '');
      oItem.emoji = '/images/question/icon_emoji_happy.png';
    }
    return oItem;
  },

  chooseSSImg(e) {// 上传ss
    let data = e.currentTarget.dataset;
    let that = this;
    my.chooseImage({
      sizeType: 'compressed',
      sourceType: ['camera'],
      count: 1,
      success: (res) => {
        my.compressImage({
          apFilePaths: res.apFilePaths,
          compressLevel: 1,
          success: path => {
            that.data.carbonList[data.index].imgList.push(path.apFilePaths[0]); //当前项的图片数组
            that.setData({
              carbonList: that.data.carbonList
            });
          }
        })
      },
      fail:(err)=>{
        if(err.error == 11){
          // console.log('手动取消')
        }else{
          my.showToast({
            content: err, // 文字内容
          });
        }
        
      }
    })
  },
  deleteImg(e) { // 删除照片
    let data = e.currentTarget.dataset;
    this.data.carbonList[data.index].imgList.splice(data.imgindex, 1);
    this.setData({
      carbonList: this.data.carbonList
    });
  },
  previewImage(e) { // 预览照片
    let data = e.currentTarget.dataset;
    my.previewImage({
      current: data.imgindex,
      urls: this.data.carbonList[data.index].imgList,
    });
  },
  openExample(e) { // 示例图
    let data = e.currentTarget.dataset;
    let arr = [data.url];
    my.previewImage({
      current: 1,
      urls: arr,
    });
    // this.setData({
    //   exampleUrl: data.url,
    //   exampleState: true,
    // })
  },
  closeExample() { // 关闭示例图弹窗
    this.setData({
      exampleState: false
    })
  },

  getScopeLocation() {
    let that = this;
    my.getSetting({
      success: (res) => {
        clearInterval(timer);
        var statu = res.authSetting;
        if (!statu.location) { //没授权
          // console.log("没授权位置信息");
          let addressLocation = {
            address: "未获取到您的位置和名称，请授权位置信息"
          }
          this.setData({
            addressLocation: addressLocation
          });
        }else{
          console.log("已授权位置信息");
          this.getAddressList()  
        }
      }
    })
  },
  getAddressList() {
    let location = app.globalData.location;
    let code = "05";
    myAmapFun.getPoiAround({
      location: location.lng+','+location.lat,
      querytypes: code,
      success: (res) => {
        let dataArr = res.poisData;
        let addressList = [];
        if(dataArr.length > 0) {
          dataArr.forEach(item => {
            let str = item.location.split(',');
            let ad = item.pname+item.cityname+item.adname;
            addressList.push({
              lng: str[0],
              lat: str[1],
              name: item.name ? item.name : '',
              address: item.address.length == 0 ? ad : item.address,
              province: item.pname,
              city: item.cityname,
              area: item.adname,
              type: item.type
            })
          })
          this.getTimes(addressList[0].name)
          this.setData({
            addressList: addressList,
            addressLocation: addressList[0],
          })
        }
      },
    })
  },
  async getTimes(keyword) {
    try{
      let params = {
        menuid: app.globalData.menuid,
        keyword: keyword
      }
      const res = await getJianSuTimes(params);
      if(res.S == 1){
        this.setData({ recordCounts: res.DataCount })
      }else{
        publicFun.showToast(res.M ? res.M : '加载失败');
      }
    }catch(e) {
      publicFun.showToast('失败，请稍后再试')
    }
  },


  getAddressInput(e) {
    let val = e.detail.value;
    let btn = false;
    if(!val){
      val = 0;
      btn = true;
    }
    this.setData({
      sreachVal: val,
      btnDisabled: btn
    })
  },
  getSreachList() {
    let that = this;
    let location = app.globalData.location;
    let locationStr = location.lng +','+ location.lat;
    myAmapFun.getInputtips({
      keywords: this.data.sreachVal,
      location: locationStr,
      success: function(data){
        if(data && data.tips.length > 0){
          let addressList = [];
          data.tips.forEach(item => {
            if(item.location.length > 0){
              let str = item.location.split(',');
              addressList.push({
                lng: str[0],
                lat: str[1],
                name: item.name ? item.name : '',
                address: item.address.length == 0 ? '' : item.address,
                province: location.province, //item.district
                city: location.city,
                area: location.district,
                type: data.tips[0].name
              })
            }else{
              addressList.push({
                name: item.name ? item.name : '',
              })
            }
          })
          that.setData({
            addressList: addressList
          })
        }
      }
    })
  },
});
